package com.junxonline.instant.admin.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.junxonline.instant.common.constant.RedisConstant;
import com.junxonline.instant.common.util.common.RedisUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 管理后台分表名称缓存初始化处理
 *
 * @author JunX
 * @date 2022-07-18
 */
@Log4j2
@Component
public class InitShardingTableCacheHandler implements CommandLineRunner {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void run(String... args) throws Exception {
        try {
            log.info("开始初始化表名称缓存..");
            redisUtils.del(RedisConstant.KEY_DATABASE_TABLES);
            List<String> tableNames = this.getAllTableNameBySchema();
            for (String tableName : tableNames) {
                redisUtils.lSet(RedisConstant.KEY_DATABASE_TABLES, tableName);
            }
            log.info("初始化表名称缓存成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化表名称缓存失败");
        }
    }

    private List<String> getAllTableNameBySchema() {
        List<String> tableNames = new ArrayList<>();
        try {
            Environment environment = SpringUtil.getApplicationContext().getEnvironment();
            Connection connection = DriverManager.getConnection(
                    Objects.requireNonNull(environment.getProperty("spring.shardingsphere.datasource.ms0.url")),
                    Objects.requireNonNull(environment.getProperty("spring.shardingsphere.datasource.ms0.username")),
                    Objects.requireNonNull(environment.getProperty("spring.shardingsphere.datasource.ms0.password"))
            );
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SHOW TABLES;");
            while (resultSet.next()) {
                tableNames.add(resultSet.getString(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tableNames;
    }

}
